package com.hjxr.quota.datasource.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.hjxr.common.core.controller.BaseController;
import com.hjxr.quota.datasource.domain.JobDatasource;
import com.hjxr.quota.datasource.domain.TablenameAlias;
import com.hjxr.quota.datasource.service.DatasourceQueryService;
import com.hjxr.quota.datasource.service.JobDatasourceService;
import com.hjxr.quota.datasource.service.TablenameAliasService;
import com.hjxr.quota.tool.query.BaseQueryTool;
import com.hjxr.quota.tool.query.QueryToolFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.Serializable;
import java.util.*;

/**
 * 数据表别名控制器层
 *
 * @author sun
 * @version v1.0
 * @since 2020-08-16
 */
@RestController
@RequestMapping("/tableAlias")
@Api(tags = "数据表别名接口")
public class TabenamAliasController extends BaseController {

    @Autowired
    private TablenameAliasService tableService;
    @Autowired
    private DatasourceQueryService datasourceQueryService;
    @Autowired
    private JobDatasourceService jobDatasourceService;

    /**
     * 转向到页面
     *
     * @return 页面地址
     */
    @GetMapping(value = "/{orgId}/{funcId}")
    private ModelAndView gotoFunc() {
        return new ModelAndView("quota/tableAlias/tableAlias");
    }

    /**
     * 分页查询所有数据
     *
     * @return 所有数据
     */
    @GetMapping
    @ApiOperation("分页查询所有数据")
    @ApiImplicitParams(
            {@ApiImplicitParam(paramType = "query", dataType = "String", name = "current", value = "当前页", defaultValue = "1", required = true),
                    @ApiImplicitParam(paramType = "query", dataType = "String", name = "size", value = "一页大小", defaultValue = "10", required = true),
                    @ApiImplicitParam(paramType = "query", dataType = "Boolean", name = "ifCount", value = "是否查询总数", defaultValue = "true"),
                    @ApiImplicitParam(paramType = "query", dataType = "String", name = "ascs", value = "升序字段，多个用逗号分隔"),
                    @ApiImplicitParam(paramType = "query", dataType = "String", name = "descs", value = "降序字段，多个用逗号分隔")
            })
    public R<IPage<TablenameAlias>> selectAll() {
        BaseForm form = new BaseForm();
        QueryWrapper<TablenameAlias> query = (QueryWrapper<TablenameAlias>) form.pageQueryWrapper(form.getParameters(), new QueryWrapper<TablenameAlias>());
        return success(tableService.page(form.getPlusPagingQueryEntity(), query));
    }

    @GetMapping("/bySource")
    @ApiOperation("根据数据源ID获取数据")
    public R<List<TablenameAlias>> selectByDatasourceId(@RequestParam(required = true) Integer datasourceId) {
        List<TablenameAlias> list = tableService.selectByDatasourceId(datasourceId);
        return success(list);
    }

    @GetMapping("/bySourceEnable")
    @ApiOperation("根据数据源ID获取数据")
    public R<List<TablenameAlias>> selectEnableByDatasourceId(@RequestParam(required = true) Integer datasourceId) {
        List<TablenameAlias> list = tableService.selectEnableByDatasourceId(datasourceId);
        return success(list);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation("通过主键查询单条数据")
    @GetMapping("{id}")
    public R<TablenameAlias> selectOne(@PathVariable Serializable id) {
        return success(this.tableService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param entity 实体对象
     * @return 新增结果
     */
    @ApiOperation("新增数据")
    @PostMapping("/addNew")
    public R<Boolean> insert(@RequestBody TablenameAlias entity) {
        return success(this.tableService.save(entity));
    }

    /**
     * 修改数据
     *
     * @param entity 实体对象
     * @return 修改结果
     */
    @PutMapping
    @ApiOperation("修改数据")
    public R<Boolean> update(@RequestBody TablenameAlias entity) {
        int result = this.tableService.update(entity);
        R<Boolean> r = success(result > 0);
        return r;
    }

    /**
     * 删除数据
     *
     * @param ids 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    @ApiOperation("删除数据")
    public R<Boolean> delete(@RequestParam("idList")  List<Integer> ids) {
        return success(this.tableService.removeByIds(ids));
    }

    /**
     * 根据数据源ID获取数据表名
     *
     * @param datosourceId 数据源ID
     * @return List<String>
     */
    @GetMapping("getTableNames")
    @ApiOperation("根据数据源ID获取数据表别名表的TABLE_NAME值")
    public R<List<String>> getTableNames(Integer datosourceId) {
        List<String> list = new ArrayList<String>();

        return success(list);
    }

    @PostMapping("/syncTables")
    @ApiOperation("同步数据源表到别名表")
    public R<Integer> syncTables(@RequestBody TablenameAlias t) {
        try {
            Integer datasourceId = t.getDatasourceId();
            List<String> tables = datasourceQueryService.getTables(datasourceId);
            JobDatasource datasource = jobDatasourceService.getById(t.getDatasourceId());

            if (datasource == null)
                return failed("数据源不存在！");
            String dbName = "";
            if("oracle".equals(datasource.getDatasource())){
                dbName = datasource.getJdbcUsername();
            }
            if("mysql".equals(datasource.getDatasource()) || "postgresql".equals(datasource.getDatasource())) {
                String[] tmp = datasource.getJdbcUrl().split("/");
                dbName = tmp[tmp.length-1];
            }
            if("sqlserver".equals(datasource.getDatasource())) {
                String[] tmp = datasource.getJdbcUrl().split("DatabaseName=");
                dbName = tmp[tmp.length-1];
            }
            if("mongodb".equals(datasource.getDatasource())) {
                dbName = datasource.getDatabaseName();
            }
            int i = 0;
            BaseQueryTool qTool = QueryToolFactory.getByDbType(datasource);

            Map<String, String> tableInfos = qTool.getTableInfos();
            for (String tableName : tableInfos.keySet()){
                if(tableService.selectByTablename(tableName, t.getDatasourceId()) == null) {
                    String comment = tableInfos.get(tableName);
                    TablenameAlias ta = new TablenameAlias();
                    ta.setDatasourceId(t.getDatasourceId());
                    ta.setTableName(tableName);
                    ta.setDatabaseName(dbName);
                    ta.setTableDesc(comment);
                    ta.setTableNameAlias(comment);
                    ta.setStatus("2");
                    ta.setUpdateBy(t.getUpdateBy());
                    ta.setUpdateDate(new Date());
                    tableService.save(ta);
                    i += 1;
                }
            }
            return success(new Integer(i));
        } catch (IOException e) {
            return failed("数据源连接失败！");
        }
    }

    @PostMapping("/batchUpdate")
    @ApiOperation("批量更新数据")
    public R<Boolean> batchUpdate(@RequestBody List<TablenameAlias> list){
        int i = 0;
        for(TablenameAlias t: list){
            i += tableService.update(t);
        }
        return success(true);
    }
//    @GetMapping("test")
//    @ApiOperation("同步数据源表到别名表")
//    public R<List<String>> test(@RequestParam(required = true) Integer datasourceId) {
//        try {
//            List<TablenameAlias> list = tableService.selectByDatasourceId(datasourceId);
//
//            return success(list);
//        } catch (IOException e) {
//            return failed("数据源连接失败！");
//        }
//    }

}

